using MediatR;
using RBAC.Domain.ProductionPlans;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ProductionPlans;
using System;
using System.Linq;

namespace RBAC.Write.Api.Application.Handler.ProductionPlans
{
    public class AddProductionPlanCommandHandler : IRequestHandler<AddProductionPlanCommands, APIResult<int>>
    {
        private readonly IBaseRepository<ProductionPlan> _planRepo;

        public AddProductionPlanCommandHandler(IBaseRepository<ProductionPlan> planRepo)
        {
            _planRepo = planRepo;
        }

        public Task<APIResult<int>> Handle(AddProductionPlanCommands request, CancellationToken cancellationToken)
        {
            try
            {
                // 基本校验
                if (string.IsNullOrWhiteSpace(request.PlanTopic))
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "计划主题不能为空", Data = 0 });
                if (string.IsNullOrWhiteSpace(request.PlanCode))
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "计划单号不能为空", Data = 0 });
                if (request.GoodsIds == null || request.GoodsIds.Count == 0)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "至少选择一个物品", Data = 0 });

                // 唯一性校验：PlanCode
                var exists = _planRepo.GetFirstOrDefault("PlanCode = @PlanCode AND IsDeleted = 0", new { request.PlanCode });
                if (exists != null)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "计划单号已存在", Data = 0 });

                // 组装批量实体
                var list = request.GoodsIds.Select(gid => new ProductionPlan
                {
                    PlanTopic = request.PlanTopic,
                    PlanCode = request.PlanCode,
                    DocumentsTime = request.DocumentsTime,
                    AssociatedProjects = request.AssociatedProjects ?? string.Empty,
                    Remark = request.Remark ?? string.Empty,
                    GoodsId = gid,
                    SaleId = request.SaleId
                }).ToList();

                // 批量写入
                var affected = _planRepo.CreateBatch(list);

                return Task.FromResult(new APIResult<int>
                {
                    Code = affected > 0 ? APIEnums.Success : APIEnums.Fail,
                    Msg = affected > 0 ? "新增生产计划成功" : "新增生产计划失败",
                    Data = affected
                });
            }
            catch (Exception ex)
            {
                return Task.FromResult(new APIResult<int>
                {
                    Code = APIEnums.Fail,
                    Msg = "新增生产计划异常: " + ex.Message,
                    Data = 0
                });
            }
        }
    }
}
